package com.fitbet.wechat.web.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.fitbet.entity.user.User;
import com.fitbet.wechat.Constant;
import com.fitbet.wechat.handler.SmsHandler;
import com.fitbet.wechat.service.DataService;

/**
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("/sms")
public class SmsController {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsController.class);
    
    @Autowired
    private SmsHandler smsHandler;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<User> userService;
    
    /**
     * 验证手机号是否已绑定用户
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/verify-mobile", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult verifyMobile(@RequestParam("mobile") String mobile) {
        
        HttpResult httpResult = new HttpResult();
        
        try {

            User user = userService.load(User.class, "mobile", mobile);
            
            if (user != null) {
                httpResult.fail("1").message("该手机号已绑定用户");
            } else {
                httpResult.success().message("该手机可用");
            }
            
        } catch (Exception e) {
            logger.error("#verifyMobile() - verify mobile failed, exception=[{}]", e);
            httpResult.fail("500").message("验证失败");
        }
        
        return httpResult;
        
    }
    
    /**
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/verify-code", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult sendVerifyCode(@RequestParam("mobile") String mobile) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            // Generate random code in 6 digits
            String code = smsHandler.generateVerifyCode(mobile);
            boolean send = smsHandler.sendVerifyCode(mobile, code);
            
            if(send) {
                
                String token = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, Constant.SMS_CLIENT));
                httpResult.success()
                          .data("token", token)
                          .message("发送短信成功");
            } else {
                logger.error("#sendVerifyCode() faild with response [{}]", JsonUtils.toJson(httpResult));
                httpResult.fail("501").message("发送短息失败");
            }
            
        } catch (Exception e) {
            logger.error("#sendVerifyCode() occurs error", e);
            httpResult.fail("500").message("发送短息请求失败");
        }
        
        return httpResult;
        
    }
    
}
